; (function ($) {
    $.fn.ajaxtable = function (options) {
        var de = {
            columns: [],
            url: "#",
            type: "GET",
            data: {},
            limit: 10,
            dataProperty: "Data",
            countProperty: "Count",
            pageProperty: "page",
            limitProerty: "limit"
    };
        var settings = $.extend({}, de, options);
        var id = $(this).attr('id');
        //console.log($(this));
        //var html = rendBox(settings.columns, id);
        //console.log(html);
        //$(this).html(html);
        //load(1);


        function renderHtml(columns, tbodyId) {
            var str = "<table class='table table-bordered table-hover dataTable' role='grid' aria-describedby='example2_info'><tr>";
            for (var i = 0; i < columns.length; i++) {
                var style = (columns[i].style || " ");
                str = str + '<td style="' + style+ '">' + (columns[i].title || "&nbsp;") + '</td>';
            }
            return str + "</tr><tboby id='" + tbodyId + "'></tbody></table>";
        }

        function renderData(columns, data) {
            var htmlBody = "";
            for (var i = 0; i < data.length; i++) {
                var row = data[i];
                htmlBody += renderRow(columns, row, i, data);
            }

            $("#" + id + " .trbody").remove();
            $("#" + id + " tbody").append(htmlBody);
        }

        function renderRow(columns, row, rowIndx, data) {
            var htmlrow = "";
            //var styles ="";
            //var cls ="";
            for (var i = 0 ; i < columns.length; i++) {
                htmlrow += renderCell(columns[i], row, rowIndx, i, data);
            }
            return "<tr class='trbody'>" + htmlrow + "</tr>";
        }

        function renderCell(column, row, rowIndx, colIndx, data) {
            var v = getData(row, column.data);
            if (typeof (column.render) === "function") {
                return "<td>" + column.render(v, row, rowIndx, colIndx, data) + "</td>";
            }
            if (v == undefined) {
                v = "";
            }
            return "<td>" + v + "</td>";
        }

        function rendPaginate(count, page, limit) {
            var pageId = id + "_paginate";
            //var infoId = id + "_info";
            $("#" + id + "_info").html("" + limit + "/" + count);
            if (count < 1) {
                $("#" + pageId).html("");
                return;
            }
            $("#" + pageId).html("<ul class='pagination'>" + renderPageBtn(Math.ceil(count / limit), Number(page)) + "</ul>");

        }

        function renderPageBtn(count, page) {

            if (count === 1 || isNaN(count)) {
                return renderPageItem(1, true, false, false, false);
            }

            var lis = "";
            //previous
            if (page > 1) {
                lis = renderPageItem(page - 1, false, false, true, false);
            }

            //
            var t = page - 3;
            if (t > 0) {
                lis += renderPageItem(t, false, false, false, false);
            }
            t = page - 2;
            if (t > 0) {
                lis += renderPageItem(t, false, false, false, false);
            }
            t = page - 1;
            if (t > 0) {
                lis += renderPageItem(t, false, false, false, false);
            }

            //activied
            lis += renderPageItem(page, true, false, false, false);

            //
            t = page + 1;
            if (t <= count) {
                lis += renderPageItem(t, false, false, false, false);
            }
            t = page + 2;
            if (t <= count) {
                lis += renderPageItem(t, false, false, false, false);
            }
            t = page + 3;
            if (t <= count) {
                lis += renderPageItem(t, false, false, false, false);
            }

            //next 
            if (page < count) {
                lis += renderPageItem(page + 1, false, false, false, true);
            }

            return lis;

        }

        function renderPageItem(page, active, disabled, previous, next) {
            var pageText = page;
            var tableIndex = page;

            var li = "<li class='paginate_button";

            if (disabled) {
                li += " disabled";
                tableIndex = 0;
            }

            if (active) {
                li += " active";
            }

            if (previous) {
                pageText = "previous";
                li += " previous";
            }
            else {
                if (next) {
                    pageText = "next";
                    li += " next";
                }
            }
            return li + "'><a href='#' class='pageItem' aria-controls='example" + Number(tableIndex) + "' data-dt-idx='" + Number(tableIndex) + "' tabindex='" + Number(tableIndex) + "'>" + pageText + "</a></li>";
        }

        function getData(data, name) {
            return data[name];
        }

        var tb = {
            id: id,
            settings: settings,
            rendBox: function () {
                var htmlBox = "<div class='box'>"
    				+ "<div class='box-body'>"
					+ "<div class='dataTables_wrapper form-inline dt-bootstrap'>"
					+ "<div class='row'><div class='col-sm-12'>"
					+ renderHtml(this.settings.columns, this.id + '_tbody')
					+ "</div></div>"
					+ "<div class='row'><div class='col-sm-5'><div id='" + id + "_info' class='dataTables_info' role='status' aria-live='polite'>0rows</div></div>"
					+ "<div class='col-sm-7'><div id='" + id + "_paginate' class='dataTables_paginate paging_simple_numbers'></div></div></div>"
					+ "</div></div></div>";
                $("#" + this.id).html(htmlBox);
            },
            setdata: function(data) {
                this.settings.data = data;
            },
            
            load: function (page) {
                var limit = this.settings.limit;
                var pageProperty = this.settings.pageProperty;
                var limitProerty = this.settings.limitProerty;
                this.settings.data[pageProperty] = page;
                this.settings.data[limitProerty] = limit;
                var d = this.settings.data;
                var columns = this.settings.columns;
                var dataProperty = this.settings.dataProperty;
                var countProperty = this.settings.countProperty;
                var me = this;
                var thisId = this.id;
                this.settings.page = page;
                $.ajax({
                    url: settings.url,
                    data: d,
                    type: settings.type,
                    success: function (data) {

                        renderData(columns, getData(data, dataProperty));

                        rendPaginate(getData(data, countProperty), page, limit);
                        $("#" + thisId).find(".pageItem").each(function() {
                            $(this).click(function() {
                                var n = $(this).attr("data-dt-idx");
                                me.load(n);
                            });
                        });
                       
                    },
                    failure: function (e, s) {
                        console.error(e);
                        console.error(s);
                    }
                });
            },
            refresh: function() {
                this.load(this.settings.page);
            }
        };
        tb.rendBox();
        return tb;

    };

})(jQuery);